package com.wnxy.sddfp.sms.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.wnxy.sddfp.sms.config.SmsTemplate;
import com.wnxy.sddfp.sms.service.ISmsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author yellow Docter
 * @date 2024 -04-15
 * @desc
 */
@Service
public class SmsService implements ISmsService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String sendMsg(String phone) {

        //防止短信轰炸的业务逻辑
        String keyCount = "SMS:" + phone + ":COUNT";
        String phoneCount = stringRedisTemplate.opsForValue().get(keyCount);
        if (StringUtils.isNotBlank(phoneCount)){ //不等于空
            if (Integer.parseInt(phoneCount) > 5) {
                System.out.println("phone 用户 " + phone + ",不能频繁获取验证码");
                return "phone 用户" + phone + ",不能频繁获取验证码";
            }
        }
        //第一次进来
        if (StringUtils.isEmpty(phoneCount)){
            //存储
            stringRedisTemplate.opsForValue().set(
                    keyCount,
                    "1",
                    3,
                    TimeUnit.MINUTES
            );
        }else{
            stringRedisTemplate.opsForValue().increment(keyCount);
        }

        //hutool 的工具类   获取4个长度的数字字符串
        String code = RandomUtil.randomNumbers(4);
        String key = "SMS:" + phone;
        // 发送到redis中
        stringRedisTemplate.opsForValue().set(
                key,
                code,
                30,          //验证码存储多久
                TimeUnit.MINUTES    //时间单位
        );
        // 发送短信
//        smsTemplate.sendSms(phone,code);
        return code;
    }

}
